<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm">
      <!--      <el-form-item>-->
      <!--        <el-input v-model="dataForm.key" placeholder="参数名" clearable></el-input>-->
      <!--      </el-form-item>-->
      <el-form-item>
        <!--        <el-button @click="getDataListByHeadId(this.dataForm.headerId)">查询</el-button>-->
        <el-button v-if="isAuth('sales:orderdetail:save')" type="primary" @click="addRow">添加</el-button>
        <el-button v-if="isAuth('sales:orderdetail:delete')" type="danger" @click="deleteHandle()"
                   :disabled="dataListSelections.length <= 0">批量删除
        </el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      :summary-method="getSummaries"
      show-summary
      v-loading="dataListLoading"
      @keyup.enter.native="addNewRow(dataList)"
      @selection-change="selectionChangeHandle"
      style="width: 100%; margin-top: 20px">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column
        prop="commodityName"
        header-align="center"
        align="center"
        width="250px"
        label="商品名称">
        <template slot-scope="scope">
          <el-autocomplete v-if="scope.row.status" v-model="scope.row.commodityName"
                           :fetch-suggestions="querySearchAsync" placeholder="请输入内容"
                           @select="handleNameSelect($event, scope.row)"
                           popper-class="select-option"
          ></el-autocomplete>
          <span v-else>{{scope.row.commodityName}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="width"
        header-align="center"
        align="center"
        label="宽">
        <template slot-scope="scope">
          <el-input v-if="scope.row.status" v-model="scope.row.width"
                    @keyup.native="scope.row.width = oninput(scope.row.width)"
                    @input="calSquares(scope.row)"></el-input>
          <span v-else>{{scope.row.width}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="height"
        header-align="center"
        align="center"
        label="高">
        <template slot-scope="scope">
          <el-input v-if="scope.row.status" v-model="scope.row.height"
                    @keyup.native="scope.row.height = oninput(scope.row.height)"
                    @input="calSquares(scope.row)"></el-input>
          <span v-else>{{scope.row.height}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="count"
        header-align="center"
        align="center"
        label="数量">
        <template slot-scope="scope">
          <el-input v-if="scope.row.status" v-model="scope.row.count"
                    @keyup.native="scope.row.count = oninput(scope.row.count)"
                    @input="calSquares(scope.row),checkByDirectionNum(scope.row)"
                    ></el-input>
          <span v-else>{{scope.row.count}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="direction"
        header-align="center"
        align="center"
        width="150px"
        label="方向">
        <template slot-scope="scope">
          <el-autocomplete v-if="scope.row.status" v-model="scope.row.direction"
                           :fetch-suggestions="querySearchDirection" placeholder="请输入内容"
                           @select="handleDirectionSelect($event, scope.row)"
                           popper-class="select-option"></el-autocomplete>
          <span v-else>{{scope.row.direction}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="squares"
        header-align="center"
        align="center"
        label="面积">
        <template slot-scope="scope">
          <!--          <el-input v-if="scope.row.status" v-model="scope.row.squares"-->
          <!--                    @keyup.native="scope.row.squares = oninput(scope.row.squares)"></el-input>-->
          <!--          <span v-else>{{scope.row.squares}}</span>-->
          <!--          不可编辑-->
          <el-input v-if="0" v-model="scope.row.squares"
                    @keyup.native="scope.row.squares = oninput(scope.row.squares)"></el-input>
          <span v-else>{{scope.row.squares}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="materialName"
        header-align="center"
        align="center"
        width="150px"
        label="板材">
        <template slot-scope="scope">
          <el-autocomplete v-if="scope.row.status" v-model="scope.row.materialName"
                           :fetch-suggestions="querySearchMaterial" placeholder="请输入内容"
                           @select="handleMaterialSelect($event, scope.row)"
                           popper-class="select-option"
          ></el-autocomplete>
          <span v-else>{{scope.row.materialName}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="colorName"
        header-align="center"
        align="center"
        width="150px"
        label="颜色">
        <template slot-scope="scope">
          <el-autocomplete v-if="scope.row.status" v-model="scope.row.colorName"
                           :fetch-suggestions="querySearchColor" placeholder="请输入内容"
                           @select="handleColorSelect($event, scope.row)"
                           popper-class="select-option"
          ></el-autocomplete>
          <span v-else>{{scope.row.colorName}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="crafts"
        header-align="center"
        align="center"
        width="150px"
        label="特殊工艺名称">
        <template slot-scope="scope">
          <span>{{scope.row.crafts}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="craftsPrice"
        header-align="center"
        align="center"
        width="150px"
        label="特殊工艺单价(元)">
        <template slot-scope="scope">
          <span>{{scope.row.craftsPrice}}</span>
        </template>
      </el-table-column>
<!--      <el-table-column-->
<!--        prop="totalCraftsPrice"-->
<!--        header-align="center"-->
<!--        align="center"-->
<!--        width="150px"-->
<!--        label="特殊工艺总价(元)">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{scope.row.totalCraftsPrice}}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column
        prop="salesAmount"
        header-align="center"
        align="center"
        label="销售金额(元)">
        <template slot-scope="scope">
          <!--          <el-input v-if="scope.row.status" v-model="scope.row.salesAmount"-->
          <!--                    ></el-input>-->
          <!--          不可编辑-->
          <el-input v-if="0" v-model="scope.row.salesAmount"
                    @keyup.native="scope.row.salesAmount = oninput(scope.row.salesAmount)"></el-input>
          <span v-else>{{scope.row.salesAmount}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="remark"
        header-align="center"
        align="center"
        width="150px"
        label="备注">
        <template slot-scope="scope">
          <el-input v-if="scope.row.status" v-model="scope.row.remark"></el-input>
          <span v-else>{{scope.row.remark}}</span>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="120"
        label="操作">
        <template slot-scope="scope">
          <!--          <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">修改</el-button>-->
          <!--          <el-button type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>-->
          <el-button class="el-icon-edit" type="primary" :disabled="scope.row.status==1"
                     size="small" circle @click.native.prevent="editRow(scope.row)"></el-button>
          <el-button class="el-icon-delete" type="danger"
                     size="small" circle @click.native.prevent="deleteRow(scope.$index, dataList)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <!--    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataListByHeadId"></add-or-update>-->
  </div>
</template>

<script>
  import AddOrUpdate from './orderdetail-add-or-update'
  import Utils from '../../../utils/event.js'

  export default {
    data () {
      return {
        dataForm: {
          headerId: 0,
          key: ''
        },
        names: [],
        directions: [],
        materials: [],
        colors: [],
        dataList: [],
        delList: [],
        salesAmount: 0,
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false
      }
    },
    components: {
      AddOrUpdate
    },
    activated () {
      this.getDataListByHeadId(this.dataForm.headerId)
    },
    methods: {
      oninput (num) {
        let str = num
        let len1 = str.substr(0, 1)
        let len2 = str.substr(1, 1)
        // 如果第一位是0，第二位不是点，就用数字把点替换掉
        if (str.length > 1 && len1 === 0 && len2 !== '.') {
          str = str.substr(1, 1)
        }
        // 第一位不能是.
        if (len1 === '.') {
          str = ''
        }
        // 限制只能输入一个小数点
        if (str.indexOf('.') !== -1) {
          let str_ = str.substr(str.indexOf('.') + 1)
          if (str_.indexOf('.') !== -1) {
            str = str.substr(0, str.indexOf('.') + str_.indexOf('.') + 1)
          }
        }
        // 正则替换
        str = str.replace(/[^\d.]/g, '') // 保留数字和小数点
        // str = str.replace(/\.\d\d\d$/, '') // 小数点后只能输两位
        return str
      },

      functionA () {
        Utils.$emit('demo', '开始调用计算优惠金额方法')
      },
      // 获取数据列表
      getDataListByHeadId (id) {
        this.dataForm.headerId = id || 0
        this.dataListLoading = true
        this.delList = []
        this.$http({
          url: this.$http.adornUrl(`/sales/orderdetail/listAllByHeadId`),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'headId': id
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataListByHeadId(this.dataForm.headerId)
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataListByHeadId(this.dataForm.headerId)
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      addNewRow (dataList) {
        if (dataList.length === 0) {

        } else {
          var n = dataList.length
          var data = dataList[n - 1]

          this.dataList.push({
            commodityId: data.commodityId,
            commodityName: data.commodityName,
            status: 1,
            // 商品单价
            commodityPrice: data.commodityPrice,
            // 商品数量
            // count: data.count,
            materialId: data.materialId,
            materialCode: data.materialCode,
            materialName: data.materialName,
            materialPrice: data.materialPrice,
            measurementId: data.measurementId,
            minSquares: data.minSquares,
            colorId: data.colorId,
            colorCode: data.colorCode,
            colorName: data.colorName,
            colorPrice: data.colorPrice,
            crafts: data.crafts,
            craftsPrice: data.craftsPrice,
            totalCraftsPrice: data.totalCraftsPrice
          })
        }
      },

      // 新增一行
      addRow () {
        this.dataList.push({
          salesAmount: 0,
          status: 1,
          // 商品单价
          commodityPrice: 0,
          // 商品数量
          count: '',
          // 板材单价
          materialPrice: 0,
          // 颜色单价
          colorPrice: 0,
          // 工艺单价
          craftsPrice: 0
        })
      },
      // 删除该行
      deleteRow (index, rows) {
        this.delList.push(rows[index].id)
        rows.splice(index, 1)
      },
      // 根据开启方向的数量检查合法性
      checkByDirectionNum (row) {
        if (!isNaN(row.directionNum) && !isNaN(row.count)) {
          let x = row.count % row.directionNum
          if (x === 0) {
            // 整除
          } else {
            row.direction = ''
            row.directionNum = 1
            row.count = 0

            this.calSquares(row)

            // 不能整除
            this.$message({
              message: '数量与开启方向不匹配',
              type: 'warning'
            })
          }
        }
      },
      // 计算面积
      calSquares (row) {
        // 计量单位ID，1为米，2为平方
        if (row.measurementId === 2) {
          if (!isNaN(row.height) && !isNaN(row.width) && !isNaN(row.count)) {
            const square = row.height * row.width / 1000000

            if (row.minSquares > square) {
              row.squares = row.minSquares * row.count
            } else {
              row.squares = parseFloat(square * row.count).toFixed(2)
            }
          } else {
            row.squares = 0
          }
        } else {
          row.squares = 0
        }

        this.calSalesAmount(row)
      },
      // 计算销售金额
      calSalesAmount (row) {
        console.log('开始计算销售金额')

        // this.calSquares(row)

        if (row.count === '') {
          row.count = 0
        }

        if (row.craftsPrice === '') {
          row.craftsPrice = '0'
        }

        row.totalCraftsPrice = row.craftsPrice * row.count

        // 计量单位ID，1为米，2为平方
        if (row.measurementId === 2) {
          // 按平方算
          // 销售金额 =  面积 *（商品单价 + 板材价格 + 颜色价格） + 工艺总价格
          row.salesAmount = parseFloat(row.squares * (row.commodityPrice + row.materialPrice + row.colorPrice) + row.totalCraftsPrice).toFixed(2)
        } else {
          // 按米算
          // 销售金额 =  高 * 商品数量 *（商品单价 + 板材价格 + 颜色价格） + 工艺总价格
          row.salesAmount = parseFloat(row.height / 1000 * row.count * (row.commodityPrice + row.materialPrice + row.colorPrice) + row.totalCraftsPrice).toFixed(2)
        }

        console.log('结束计算销售金额')
      },
      editRow (row) {
        row.status = 1
      },
      // 批量删除
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/sales/orderdetail/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataListByHeadId(this.dataForm.headerId)
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      // 合计
      getSummaries (param) {
        const {columns, data} = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 1) {
            sums[index] = '合计'
            return
          }
          const values = data.map(item => Number(item[column.property]))
          // 销售金额(元)
          if (column.property === 'salesAmount') {
            if (!values.every(value => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0)
              sums[index] += ''
            } else {
              sums[index] = ''
            }

            sums[index] = parseFloat(sums[index]).toFixed(2)

            this.salesAmount = sums[index]
            this.functionA()
          }
          // 数量
          if (column.property === 'count') {
            if (!values.every(value => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0)
              sums[index] += ''
            } else {
              sums[index] = ''
            }
          }
        })

        return sums
      },
      // 商品名称 远程搜索
      // queryString 为在框中输入的值
      // callback 回调函数,将处理好的数据推回
      querySearchAsync (queryString, callback) {
        this.s_girard = queryString === '' || queryString === null ? 'undefined' : queryString
        this.loading = true
        this.$http({
          url: this.$http.adornUrl(`/sto/commodity/listCommoditys/${this.s_girard}`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.names = data.commoditysMap.commodityNameDtoList
          } else {
            this.names = []
          }
        })
        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          callback(this.names)
        }, 1000)
        // callback(this.names)
      },
      // 开启方向 远程搜索
      // queryString 为在框中输入的值
      // callback 回调函数,将处理好的数据推回
      querySearchDirection (queryString, callback) {
        this.s_girard = queryString === '' || queryString === null ? 'undefined' : queryString
        this.loading = true
        this.$http({
          url: this.$http.adornUrl(`/sto/direction/listDirections/${this.s_girard}`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.directions = data.directionsMap.directionDtoList
          } else {
            this.directions = []
          }
        })
        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          callback(this.directions)
        }, 1000)
        // callback(this.directions)
      },
      // 板材 远程搜索
      // queryString 为在框中输入的值
      // callback 回调函数,将处理好的数据推回
      querySearchMaterial (queryString, callback) {
        this.s_girard = queryString === '' || queryString === null ? 'undefined' : queryString
        this.loading = true
        this.$http({
          url: this.$http.adornUrl(`/sto/material/listMaterials/${this.s_girard}`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.materials = data.materialsMap.materialDtoList
          } else {
            this.materials = []
          }
        })
        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          callback(this.materials)
        }, 500)
        // callback(this.materials)
      },
      // 颜色 远程搜索
      // queryString 为在框中输入的值
      // callback 回调函数,将处理好的数据推回
      querySearchColor (queryString, callback) {
        this.s_girard = queryString === '' || queryString === null ? 'undefined' : queryString
        this.loading = true
        this.$http({
          url: this.$http.adornUrl(`/sto/color/listColors/${this.s_girard}`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.colors = data.colorsMap.colorDtoList
          } else {
            this.colors = []
          }
        })
        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          callback(this.colors)
        }, 500)
        // callback(this.colors)
      },
      handleSelect (item) {
        console.log(item)
        // do something
      },
      handleNameSelect (item, row) {
        console.log(item)
        row.commodityName = item.commodityName
        row.commodityId = item.commodityId
        row.commodityPrice = item.commodityPrice
        row.crafts = item.craftName
        row.craftsPrice = item.craftPrice
        row.totalCraftsPrice = item.craftPrice * row.count
        row.measurementId = item.measurementId
        row.minSquares = item.minSquares
        this.calSquares(row)
      },

      handleMaterialSelect (item, row) {
        console.log(item)
        row.materialPrice = item.materialPrice
        row.materialCode = item.materialCode
        row.materialId = item.materialId
        this.calSquares(row)
      },
      handleDirectionSelect (item, row) {
        console.log(item)
        row.directionNum = item.directionNum
        this.checkByDirectionNum(row)
      },
      handleColorSelect (item, row) {
        console.log(item)
        row.colorPrice = item.colorPrice
        row.colorId = item.colorId
        this.calSquares(row)
      }
    }
  }
</script>
<style lang="scss" scoped>
  .select-option {
    width: 600px;
  }
</style>
